﻿CREATE FUNCTION RATE_IR(
	@AF float,
	@PMT numeric(18,2),
	@NumberOfPayments smallint,
	@OpenDate smalldatetime,
	@FstDueDate smalldatetime,
	@PaymentsPerYear tinyint,
	@DayCountConvention tinyint
)RETURNS float WITH SCHEMABINDING
BEGIN

IF @PMT IS NULL OR @PMT <= 0 OR ISNULL(@AF,0) = 0  OR ISNULL(@NumberOfPayments,0) = 0 RETURN NULL

DECLARE @SP int SET @SP = dbo.BaseDays(@FstDueDate,@DayCountConvention)/@PaymentsPerYear --Standard Period
DECLARE @DTF int/*Days to First Pmt*/SET @DTF = DATEDIFF(dd,@OpenDate,@FstDueDate)
IF @DTF < 0 SET @DTF = 1
DECLARE @FNP float/*No Periods to First Pmt*/SET @FNP = @DTF/@SP
DECLARE @FND  float/*No Odd Days to First Pmt*/SET @FND = @DTF-@FNP*@SP
DECLARE @ODF  float/*Odd Days Factor*/SET @ODF = @FND/@SP
RETURN (@PMT*@NumberOfPayments-@AF)/(@NumberOfPayments+(@FNP-1)+@ODF)*@PaymentsPerYear/@AF
--PRINT dbo.RATE_IR(10400.98,218.13,72,'1/1/2008','1/16/2008',24,1)
END




